﻿using AutoMapper;
using ERP.BLL.UserApp;
using ERP.BLL.UserApp.Dtos;
using ERP.Common.Utils;
using ERP.Web.Core.Authentication.JwtBearer;
using ERP.Web.Mvc.Basic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;

namespace ERP.Web.Mvc.Controllers
{

    public class LoginController : OperationControllerBase
    {
        private readonly IUserService _userService;
        private readonly TokenProviderOptions _options;
        public LoginController(IUserService userService, TokenProviderOptions options)
        {
            _userService = userService;
            _options = options;
        }

        #region 用户登录校验
        [AllowAnonymous]
        [HttpPost]
        public Task<object> Login(string loginName, string password)
        {
            //获取用户状态
            var userStatus = _userService.ValidateUser(loginName, password);
            string msg;
            switch (userStatus)
            {
                case UserExceptionCode.USER_NOT_EXIST:
                    msg = "user is not exist";
                    break;
                case UserExceptionCode.USER_PASSWORD_ERROR:
                    msg = "user password error";
                    break;

                case UserExceptionCode.BLACK_USER:
                    msg = "user is black";
                    break;

                case UserExceptionCode.USER_ACCESS_EXCEPTION:
                    msg = "access service error";
                    break;
                default:
                    msg = "user can login";
                    var user = _userService.GetUser(loginName);
                    var userInfo = Mapper.Map<UserInfo>(user);
                    var userRoleIds = user.UserRoleDtos.Select(t => t.RoleId).ToList().ConvertAll(t => t.ToString());
                    var token = JwtToken.BuildJwtToken(loginName, userRoleIds, _options);

                    return Task.FromResult<object>(new { Message = msg, Token = new { Value = token, User = userInfo } });
            }
            return Task.FromResult<object>(new { Message = msg });
        }

        #endregion

        #region 退出登录
        [HttpGet("api/logout")]
        public IActionResult Logout()
        {
            return Json(new { Success = true });
        }
        #endregion
    }
}